<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="员工姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入员工姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="工号" prop="numbe">
        <el-input
          v-model="queryParams.numbe"
          placeholder="请输入职务"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['business:vacationList:query']"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:vacationList:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:vacationList:del']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:vacationList:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="holidayList"
      max-height="650px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column
        label="适用区域"
        align="center"
        prop="regionName"
        width="160"
      />
      <el-table-column
        label="归属门店"
        align="center"
        prop="storeName"
        width="160"
      />
      <el-table-column label="员工姓名" align="center" prop="userName" />
      <!-- <el-table-column label="工号" align="center" prop="numbe" /> -->
      <el-table-column label="职务" align="center" prop="job" />
      <el-table-column
        label="电话"
        align="center"
        prop="phoneNumber"
        width="160"
      />
      <el-table-column label="休假类型" align="center" prop="typeName" />
      <el-table-column label="审批状态" align="center" prop="state" width="120">
        <template slot-scope="scope">
          <span>{{
            scope.row.state === "0"
              ? "未审核"
              : scope.row.state === "1"
              ? "通过"
              : scope.row.state === "2"
              ? "不通过"
              : ""
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="审批人" align="center" prop="approverName" />
      <el-table-column label="审批时间" align="center" prop="approverTime" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approverTime, "{y}-{m}-{d}") }}</span>
        </template>
        </el-table-column>

      <!-- <el-table-column label="休假开始时间" align="center" prop="storeId" />
      <el-table-column label="休假结束时间" align="center" prop="storeName" /> -->
      <el-table-column
        label="请假开始时间"
        align="center"
        prop="beginTime"
        width="120"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
       <el-table-column
        label="请假结束时间"
        align="center"
        prop="endTime"
        width="120"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="创建人"   align="center"  prop="createBy" />
      <el-table-column label="创建时间"   align="center"  prop="createTime" />
      <el-table-column label="修改人"   align="center"  prop="updateBy" />
      <el-table-column label="修改时间"   align="center"  prop="updateTime" />
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
        width="250"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button> -->

          <div>
            <el-button
              size="mini"
              v-if="scope.row.state != '2'"
              type="text"
              @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <el-button
              v-if="scope.row.state == '0'"
              size="mini"
              type="text"
              @click="handleGround(scope.row, (state = 1))"
              v-hasPermi="['business:vacationList:pass']"
              >通过</el-button
            >
            <el-button
              size="mini"
              v-if="scope.row.state == '0'"
              type="text"
              @click="handleGround(scope.row, (state = 2))"
              v-hasPermi="['business:vacationList:fail']"
              >不通过</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              v-hasPermi="['business:vacationList:del']"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改休假规则对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="区域" prop="regionId">
          <el-select
            clearable
            v-model="form.regionId"
            @change="changeRegion"
            :disabled="title == '修改休假'"
          >
            <el-option
              v-for="(item, index) of region"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="适用门店" prop="storeId">
          <el-select
            clearable
            v-model="form.storeId"
            @change="changeStore"
            :disabled="title == '修改休假'"
          >
            <el-option
              v-for="(item, index) of store"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="请假技师" prop="type">
          <el-input v-model="form.type" placeholder="请输入请假类型" />
        </el-form-item> -->
        <el-form-item label="角色" prop="roleId">
          <el-select
            clearable
            v-model="form.roleId"
            @change="changeRole"
            :disabled="title == '修改休假'"
          >
            <el-option
              v-for="(item, index) of holidayRoleS"
              :key="index"
              :label="item.roleName"
              :value="item.roleId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="休假人" prop="zyTechnicianId">
          <el-input
            v-model="form.userName"
            disabled
            v-if="title == '修改休假'"
            style="width: 220px"
          ></el-input>
          <el-select clearable v-model="form.zyTechnicianId" v-else>
            <el-option
              v-for="(item, index) of jishi"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="工号" prop="numbe">
          <el-input
            v-model="form.numbe"
            placeholder="请输入工号"
            style="width: 222px"
          />
        </el-form-item> -->
        <el-form-item label="请假类型" prop="type">
          <el-select clearable v-model="form.type">
            <el-option
              v-for="(item, index) of listrule"
              :key="index"
              :label="item.label"
              :value="item.value"
              >{{ item.label }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="请假时间" prop="time">
          <el-date-picker
            v-model="time"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="getTime"
            type="datetimerange"
            :picker-options="pickerOptions"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>

        <!-- <el-form-item label="请假开始时间" prop="beginTime">
          <el-date-picker
            clearable
            v-model="form.beginTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择请假开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="请假结束时间" prop="endTime">
          <el-date-picker
            clearable
            v-model="form.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择请假结束时间"
          >
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="请假原因" prop="reason">
          <el-input
            type="textarea"
            v-model="form.reason"
            placeholder="请输入请假原因"
            style="width: 250px"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listholiday,
  getholiday,
  delHoliday,
  addHoliday,
  updateholiday,
  listMemberRegion,
  listMemberStore,
  listtechnicianList,
  holidayPut,
  getUserByRole,
  holidayCheckLeaveDays,
} from "@/api/system/personnelMatters/vacationList";
import {
  listrule,
  getHolidayRole,
} from "@/api/system/personnelMatters/vacationRule";
export default {
  name: "Holiday",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 休假规则表格数据
      holidayList: [],
      time: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        userName: null,
        numbe: null,
        job: null,
        phoneNumber: null,
        regionId: null,
        regionName: null,
        storeId: null,
        storeName: null,
        type: null,
        state: null,
        beginTime: null,
        endTime: null,
        reason: null,
        zyTechnicianId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        beginTime: [
          { required: true, message: "请选择请假开始时间", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "请选择请假结束时间", trigger: "blur" },
        ],
      },
      store: [],
      region: [],
      listrule: [],
      jishi: [],
      storeId: "",
      holidayRoleS: [],
      pickerOptions: {
        disabledDate(v) {
          return v.getTime() < new Date().getTime() - 86400000; //  - 86400000是否包括当天
        },
      },
    };
  },
  watch: {
    "form.regionId": {
      handler: function (newVal) {
        if (newVal) {
          const regionId = newVal;
          this.$nextTick(() => {
            listMemberStore({ regionId }).then((res) => {
              this.store = res.data.map((rItem) => {
                return {
                  key: rItem.id,
                  value: rItem.storeName,
                };
              });
            });
          });
        }
      },
    },
    // "form.storeId": {
    //   handler: function (newVal) {
    //     if (newVal) {
    //       const belongStoreId = newVal;
    //       this.$nextTick(() => {

    //       });
    //     }
    //   },
    //   deep:true
    // },
  },
  created() {
    this.getList();
    this.getRuleList();
    this.listregion();
    this.getRoleList();
  },
  methods: {
    getRoleList() {
      getHolidayRole().then((res) => {
        this.holidayRoleS = res.rows;
      });
    },
    getRuleList() {
      listrule({
        isInitiate: 1,
        effectiveRoleIds: [this.form.roleId],
        storeId: this.form.storeId,
      }).then((res) => {
        this.listrule = res.rows.map((rItem) => {
          return {
            value: rItem.id,
            label: rItem.type,
          };
        });
        // this.listrule = this.listrule.filter(item => item.id !== item.id);
      });
    },
    listregion() {
      listMemberRegion().then((res) => {
        this.region = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.regionName,
          };
        });
      });
    },
    getJishiList() {
      getUserByRole({
        belongStoreId: this.form.storeId,
        roleId: this.form.roleId,
      }).then((res) => {
        this.jishi = res.data.map((rItem) => {
          return {
            key: rItem.userId,
            value: rItem.userName,
          };
        });
      });
    },
    changeRegion(value) {
      // const selectedOption = this.region.find((item) => item.key === value);
      // const selectedKey = selectedOption.key;
      // const selectedValue = selectedOption.value;
      // console.log(`Selected Key: ${selectedKey}`);
      // console.log(`Selected Value: ${selectedValue}`);
      this.form.storeId = "";
      this.form.zyTechnicianId = "";
      this.form.roleId = "";
      this.form.type = "";
      this.time = [];
      this.form.reason=''
    },
    changeStore(value) {
      // const selectedOption = this.store.find((item) => item.key === value);
      // const selectedKey = selectedOption.key;
      // const selectedValue = selectedOption.value;
      // console.log(`Selected Key: ${selectedKey}`);
      // console.log(`Selected Value: ${selectedValue}`);
      // this.form.storeName = selectedValue;
      // console.log(this.form.storeName, 555);
      // this.storeId = value
      this.form.storeId = value;
      this.form.zyTechnicianId = "";
      this.form.type = "";
      this.form.roleId = "";
      this.form.reason=''
      this.time = [];
      this.jishi = [];
      this.listrule = [];
      // this.getJishiList();
      this.getRuleList();
    },
    changeRole(value) {
      this.form.roleId = value;
      this.form.zyTechnicianId = "";
      this.jishi = [];
      this.listrule = [];
      this.getJishiList();
      this.getRuleList();
    },
    /** 查询休假规则列表 */
    getList() {
      this.loading = true;
      listholiday(this.queryParams).then((response) => {
        this.holidayList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleGround(row, state) {
      let params = {
        id: row.id,
        state: state,
      };

      let obj = {
        beginTime: row.beginTime,
        endTime: row.endTime,
        type: row.type,
        zyTechnicianId: row.zyTechnicianId,
      };
      return new Promise((resolve, reject) => {
        holidayCheckLeaveDays(obj).then((res) => {
          let _this = this;
          if (res.code == 200) {
            if (res.data.ifExceed && res.data.exceedDay != "") {
              this.$confirm(res.data.exceedDay + "是否确定通过", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(function () {
                  holidayPut(params).then((res) => {
                    if (res.code == 200) {
                      _this.$message({
                        type: "success",
                        message: `${state == "1" ? "通过" : "不通过"}成功!`,
                      });
                    }

                    _this.getList();
                  });
                })
                .catch(() => {});
            } else {
              holidayPut(params).then((res) => {
                if (res.code == 200) {
                  _this.$message({
                    type: "success",
                    message: `${state == "1" ? "通过" : "不通过"}成功!`,
                  });
                }

                _this.getList();
              });
            }
          }
        });
      });

      return;
      let _this = this;
      this.$confirm(
        `此操作将${state == "1" ? "通过" : "不通过"}该数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          holidayPut(params).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: `${state == "1" ? "通过" : "不通过"}成功!`,
              });
            }

            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        userName: null,
        numbe: null,
        job: null,
        phoneNumber: null,
        regionId: null,
        regionName: null,
        storeId: null,
        storeName: null,
        type: null,
        state: null,
        beginTime: null,
        endTime: null,
        createBy: null,
        createTime: null,
        updateTime: null,
        reason: null,
        zyTechnicianId: null,
        roleId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加休假";
      this.jishi = [];
      this.time = [];
      this.store = [];
      this.listrule = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getholiday(id).then((response) => {
        this.form = response.data;
        this.form.roleId = response.data.jobId;
        this.form.zyTechnicianId = response.data.userId;

        this.time = [this.form.beginTime, this.form.endTime];
        this.open = true;
        this.title = "修改休假";
        this.jishi = [];
        this.store = [];
        this.listrule = [];
        this.getRuleList();
        this.getJishiList();
      });
    },
    // 判断休假天数
    checkLeaveDays() {
      let obj = {
        beginTime: this.form.beginTime,
        endTime: this.form.endTime,
        type: this.form.type,
        zyTechnicianId: this.form.zyTechnicianId,
      };

      return new Promise((resolve, reject) => {
        holidayCheckLeaveDays(obj).then((res) => {
          let _this = this;
          if (res.code == 200) {
            if (res.data.ifExceed && res.data.exceedDay != "") {
              this.$modal
                .confirm(res.data.exceedDay + "是否确定继续提交")
                .then(function () {
                  if (_this.form.id != null) {
                    updateholiday(_this.form).then((response) => {
                      if (response.code == 200) {
                        _this.$modal.msgSuccess("修改成功");
                        _this.open = false;
                        _this.getList();
                      }
                    });
                  } else {
                    addHoliday(_this.form).then((response) => {
                      if (response.code == 200) {
                        _this.$modal.msgSuccess("新增成功");
                        _this.open = false;
                        _this.getList();
                      }
                    });
                  }
                  _this.open = false;
                })
                .catch(() => {});
            } else {
              if (this.form.id != null) {
                updateholiday(this.form).then((response) => {
                  if (response.code == 200) {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  }
                });
              } else {
                addHoliday(this.form).then((response) => {
                  if (response.code == 200) {
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  }
                });
              }
              this.open = false;
            }
          }
        });
      });
    },
    getTime() {
      this.form.beginTime = this.time[0];
      this.form.endTime = this.time[1];
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (new Date(this.form.endTime) < new Date(this.form.beginTime)) {
          this.$modal.msgWarning("开始时间大于结束时间");
          return;
        }

        if (valid) {
          this.checkLeaveDays();
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除姓名为"' + row.userName + '"的数据项？')
        .then(function () {
          return delHoliday(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/holiday/export",
        {
          ...this.queryParams,
        },
        `holiday_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style>
.dialog-footer {
  text-align: center;
}
</style>
